#include "polarplotwidget.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QMessageBox>
#include <QFileDialog>
#include <cmath>


PolarPlotWidget::PolarPlotWidget(QWidget *parent) : QWidget(parent)
{
    setBackgroundRole(QPalette::Light);
    setAutoFillBackground(true);
}

void PolarPlotWidget::setData(const QVector<PolarPoint> &data)
{
    m_data = data;
    update();  // 触发重绘
}

bool PolarPlotWidget::saveImage(const QString &filePath)
{
    // 创建与窗口大小相同的图像
    QImage image(size(), QImage::Format_ARGB32);
    image.fill(Qt::white);

    // 在图像上绘制
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing);

    // 手动触发绘图事件到图像上
    QRect drawArea = image.rect().adjusted(20, 20, -20, -20);
    double scale = calculateScaleFactor(drawArea);

    // 绘制网格和坐标轴
    painter.save();
    painter.translate(drawArea.center());

    // 绘制同心圆网格
    QPen gridPen(Qt::lightGray, 1);
    painter.setPen(gridPen);
    int gridCount = 5;
    for (int i = 1; i <= gridCount; ++i) {
        double gridRadius = (drawArea.width() / 2.0) * i / gridCount;
        painter.drawEllipse(QPointF(0, 0), gridRadius, gridRadius);
    }

    // 绘制角度线
    for (int angle = 0; angle < 360; angle += 30) {
        double rad = angle * M_PI / 180.0;
        double x = cos(rad) * (drawArea.width() / 2.0) * scale;
        double y = -sin(rad) * (drawArea.height() / 2.0) * scale; // y轴方向相反
        painter.drawLine(QPointF(0, 0), QPointF(x, y));
    }

    // 绘制坐标轴标签
    painter.setPen(Qt::black);
    painter.drawText(drawArea.width()/2 + 5, 0, "0°");
    painter.drawText(0, -drawArea.height()/2 - 5, "90°");
    painter.drawText(-drawArea.width()/2 - 20, 0, "180°");
    painter.drawText(0, drawArea.height()/2 + 15, "270°");

    painter.restore();

    // 绘制数据曲线
    if (!m_data.isEmpty()) {
        // 转换极坐标到笛卡尔坐标
        m_cartesianPoints.clear();
        for (const auto& point : m_data) {
            m_cartesianPoints.append(polarToCartesian(point.angle, point.radius, drawArea));
        }

        QPen curvePen(Qt::red, 2);
        painter.setPen(curvePen);
        painter.drawPolyline(m_cartesianPoints.data(), m_cartesianPoints.size());
//        painter.drawPoints(m_cartesianPoints.data(), m_cartesianPoints.size());
    }

    // 保存图像
    return image.save(filePath);
}

void PolarPlotWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘图区域，留出边距
    QRect drawArea = rect().adjusted(20, 20, -20, -20);

    // 绘制网格和坐标轴
    painter.save();
    painter.translate(drawArea.center());

    // 绘制同心圆网格
    QPen gridPen(Qt::lightGray, 1);
    painter.setPen(gridPen);
    int gridCount = 5;
    for (int i = 1; i <= gridCount; ++i) {
        double gridRadius = (drawArea.width() / 2.0) * i / gridCount;
        painter.drawEllipse(QPointF(0, 0), gridRadius, gridRadius);
    }

    // 绘制角度线
    for (int angle = 0; angle < 360; angle += 30) {
        double rad = angle * M_PI / 180.0;
        double x = cos(rad) * (drawArea.width() / 2.0);
        double y = -sin(rad) * (drawArea.height() / 2.0); // y轴方向相反
        painter.drawLine(QPointF(0, 0), QPointF(x, y));
    }

    // 绘制坐标轴标签
    painter.setPen(Qt::black);
    painter.drawText(drawArea.width()/2 + 5, 0, "0°");
    painter.drawText(0, -drawArea.height()/2 - 5, "90°");
    painter.drawText(-drawArea.width()/2 - 20, 0, "180°");
    painter.drawText(0, drawArea.height()/2 + 15, "270°");

    painter.restore();

    // 绘制数据曲线
    if (!m_data.isEmpty()) {
        // 转换极坐标到笛卡尔坐标
        m_cartesianPoints.clear();
        for (const auto& point : m_data) {
            m_cartesianPoints.append(polarToCartesian(point.angle, point.radius, drawArea));
        }

        QPen curvePen(Qt::red, 2);
        painter.setPen(curvePen);
        painter.drawPolyline(m_cartesianPoints.data(), m_cartesianPoints.size());
//        painter.drawPoints(m_cartesianPoints.data(), m_cartesianPoints.size());
    }
}

QPointF PolarPlotWidget::polarToCartesian(double angle, double radius, const QRect &drawArea)
{
    // 计算缩放因子
    double scale = calculateScaleFactor(drawArea);

    // 极坐标转笛卡尔坐标
    double x = radius * cos(angle) * scale;
    double y = -radius * sin(angle) * scale;  // 负号是因为Qt的y轴向下

    // 转换到绘图区域的坐标系统（中心为原点）
    return QPointF(drawArea.center().x() + x, drawArea.center().y() + y);
}

double PolarPlotWidget::calculateScaleFactor(const QRect &drawArea)
{
    if (m_data.isEmpty()) return 1.0;

    // 找到最大半径
    double maxRadius = 0;
    for (const auto& point : m_data) {
        if (point.radius > maxRadius) {
            maxRadius = point.radius;
        }
    }

    if (maxRadius <= 0) return 1.0;

    // 计算缩放因子，使最大半径的点刚好在绘图区域内
    double maxDimension = qMin(drawArea.width(), drawArea.height()) / 2.0;
    return maxDimension / maxRadius * 0.9;  // 0.9留一些余量
}

